<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
		<uni-forms err-show-type="toast" ref="formRef" :model="formData" :rules="formRules" labelWidth="80px">
			<!--采购单信息-->
			<view class="detail-item">
				<uni-section title="采购单信息" type="line"></uni-section>
				<view class="detail-content formRef">
					  <uni-forms-item label="供应商" name="supplierId" required>
					    <uni-data-select
					    	v-model="formData.supplierId"
					    	placeholder="请选择供应商"
								@change="changeSupplier"
					    	:localdata="supplierList"></uni-data-select>
					  </uni-forms-item>
						<uni-forms-item label="仓库名称" name="warehouseId" required>
						  <uni-data-select
						  	v-model="formData.warehouseId"
						  	placeholder="请选择仓库"
								@change="changeWarehouseId"
						  	:localdata="warehouseSortingList"></uni-data-select>
						</uni-forms-item>
				</view>
			</view>
			
			<!--商品清单-->
			<view class="detail-item">
				<view class="main-flex">
					<uni-section title="商品清单" type="line"></uni-section>
					<!--操作-->
					<view class="operate main-flex">
						<up-button
							class="operate-btn main-flex"
							size="mini"
							type="primary"
							@click="addFun">
							<uni-icons class="operate-btn-icon" type="plusempty" size="28rpx" color="#ffffff"></uni-icons>
							<view class="operate-btn-text">新增</view>
						</up-button>
					</view>
				</view>
				<view class="detail-content table">
					<ty-table
						:data="chooseProductList"
						:columns="columns"
						:sortable="true"
						:cellClassName="() => 'table-cell'"
						:headerCellClassName="() => 'table-cell'"
						:rowClassName="() => 'table-row'"
						stripe
						border>
						<template v-slot:table1="{ row }">
							<view class="table-td-cell">
								<view class="table-td-row main-flex" style="overflow: hidden;">
									商品：
									<text class="table-td-text main-flex-item">{{row.productName}}</text>
								</view>
								<view class="table-td-row main-flex">
									类型：
									<text class="table-td-text main-flex-item">{{row.typeName}}</text>
								</view>
								<view class="table-td-row main-flex">
									单位：
									<text class="table-td-text main-flex-item">{{row.productUnit}}</text>
								</view>
							</view>
						</template>
						<template v-slot:table2="{ row }">
							<view class="table-td-cell">
								<view class="table-td-row main-flex">
									采购价：
									<text class="table-td-text price">￥{{row.purchasePrice}}</text>
								</view>
								<view class="table-td-row main-flex">
									数量：
									<view class="table-td-input">
										<uni-number-box @change="changeProductCount($event, row)" background="#007aff" color="#ffffff" v-model="row.productCount" ></uni-number-box>
									</view>
								</view>
								<view class="table-td-row main-flex">
									合计：
									<text class="table-td-text price">￥{{row.purchaseMoney}}</text>
								</view>
							</view>
						</template>
						
						<template v-slot:table3="{ row }">
							<view class="table-td-cell">
								<view class="table-td-row main-flex">
									<up-button
										class="operate-btn main-flex"
										size="mini"
										type="primary"
										@click="searchFun(row)">
										<uni-icons class="operate-btn-icon" type="search" size="28rpx" color="#ffffff"></uni-icons>
										<view class="operate-btn-text">库存</view>
									</up-button>
								</view>
								<view class="table-td-row main-flex">
									<up-button
										class="operate-btn main-flex"
										size="mini"
										type="error"
										@click="delFun(row)">
										<uni-icons class="operate-btn-icon" type="trash" size="28rpx" color="#ffffff"></uni-icons>
										<view class="operate-btn-text">删除</view>
									</up-button>
								</view>
							</view>
						</template>
						<template v-slot:empty>
							<view class="table-empty">
								<up-empty mode="data"/>
							</view>
						</template>
					</ty-table>
				</view>
				
				<uni-section title="采购单金额" type="line"></uni-section>
				<view class="detail-content formRef">
					<uni-forms-item label="其他金额" name="otherPrice">
						<uni-easyinput type="number" v-model="formData.otherPrice" placeholder="请输入其他金额" />
					</uni-forms-item>
					<uni-forms-item label="优惠金额" name="discountPrice">
						<uni-easyinput type="number" v-model="formData.discountPrice" placeholder="请输入优惠金额" />
					</uni-forms-item>
					<uni-forms-item label="采购总金额" name="allPrice">
						<uni-easyinput type="number" disabled v-model="formData.allPrice" placeholder="请输入采购总金额" />
					</uni-forms-item>
					<uni-forms-item label="采购说明" name="remark">
						<uni-easyinput type="textarea" v-model="formData.remark" placeholder="请输入采购说明"></uni-easyinput>
					</uni-forms-item>
				</view>
				
			</view>
			
			<view class="formRef-btn">
				<button type="primary" :disabled="isSubmit" :loading="isSubmit" @click="submit">提交</button>
			</view>
			</uni-forms>
		</view>
		
		
		<!--商品选择-->
		<ty-supplier-product-picker 
			:showProduct="showProduct"
			:supplierId="formData.supplierId"
			@change="changeProduct"
			@close="closeProduct">
		</ty-supplier-product-picker>
		<!--商品库存-->
		<ty-storage-product-picker 
			:showStorage="showStorage"
			:warehouseList="warehouseDeliveryList"
			:warehouseId="formData.warehouseId"
			:searchProductName="searchProductName"
			@close="closeStorage">
		</ty-storage-product-picker>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref, watch } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import useUserStore from '@/store/modules/user'
import { timeFormat } from 'uview-plus'
import { supplier, allSupplier, supplierProductById, purchaseOrderAdd } from "@/api/erp_api/purchase"
import { warehouse } from "@/api/erp_api/warehouse"
import useSetStore from '@/store/modules/set'
import { Decimal } from 'decimal.js'

	const userStore = useUserStore()
	const setStore = useSetStore()
	onLoad((option) => {
		getAllWarehouse()
		getAllSupplier()
		init()
	})
	
	// 获取仓库
	const warehouseList = ref([])
	const warehouseDeliveryList = ref([])
	const getAllWarehouse = () => {
		warehouse().then(res => {
			warehouseList.value = res.rows.filter(item => item.status === 0).map(item => {
				return {
					...item,
					value: item.id,
					text: item.name
				}
			}) || []
			const list = warehouseList.value.filter(item => item.type === 'sorting')
			if (list.length > 0) {
				formData.value.warehouseId = list[0].id
				changeWarehouseId(list[0].id)
			}
		})
	}
	
	const warehouseSortingList = computed(() => {
		return warehouseList.value.filter(item => item.type === 'sorting')
	})
	// 切换仓库
	const changeWarehouseId = (e) => {
		const list = warehouseList.value.filter(item => item.type === 'delivery' && item.parentId == e)
		const warehouseSortingList = warehouseList.value.filter(item => item.id == e)
		warehouseDeliveryList.value = warehouseSortingList.concat(list)
	}
	// 获取供应商
	const supplierList = ref()
	const getAllSupplier = () => {
		allSupplier().then(res => {
			supplierList.value = res.data.map(item => {
				return {
					...item,
					value: item.id,
					text: item.name
				}
			}) || []
		})
	}
	// 切换供应商
	const changeSupplier = (e) => {
		// console.log(e)
		getSupplierProductList(e)
	}
	// 获取供应商商品
	const supplierProductList = ref([])
	const getSupplierProductList = (id) => {
		supplierProductById({
			supplierId: id
		}).then(res => {
			supplierProductList.value = res.data || []
			if (productList.value.length > 0) {
				chooseProductList.value = productList.value.map(item => {
					const supplierProduct = supplierProductList.value.find(item1 => item1.productId === item.productId)
					return {
						...item,
						typeName: supplierProduct?.typeName || '',
						purchasePrice: supplierProduct?.purchasePrice || 0,
						supplierProduct: supplierProduct || null,
						purchaseMoney: purchaseMoney(supplierProduct?.purchasePrice || 0, item.productCount)
					}
				})
			} else {
				chooseProductList.value = []
			}
		})
	}
	
	// 初始
	const supplierId = ref('')
	const productList = ref([])
	const init = () => {
		const purchaseOrder = { ...setStore.purchaseOrder }
		// const purchaseOrder = uni.getStorageSync('purchaseOrder')
		// console.log(purchaseOrder)
		if (purchaseOrder?.supplierId) {
			supplierId.value = purchaseOrder.supplierId
			formData.value.supplierId = supplierId.value
			getSupplierProductList(supplierId.value)
		}
		if (purchaseOrder?.productList) {
			productList.value = purchaseOrder.productList
		}
	}
	
	// 采购的商品
	const chooseProductList = ref([])
	// 表格头部
	const columns = ref([
		{ title: '商品信息', key: 'table1' },
		{ title: '价格信息', key: 'table2', width: '140px' },
		{ title: '操作', key: 'table3', width: '60px' }
	])
	
	// form表单数据
	const formData = ref({
		allPrice: 0,
		discountPrice: '',
		otherPrice: '',
		remark: '',
		supplierId: '',
		warehouseId: ''
	})
	const formRef = ref(null)
	const formRules = ref({
		supplierId: {
			rules: [{ required: true, errorMessage: '请选择供应商' }]
		},
		warehouseId: {
			rules: [{ required: true, errorMessage: '请选择仓库' }]
		}
	})
	const isSubmit = ref(false)
	// 提交
	const submit = () => {
		formRef.value.validate().then(formRes => {
			const isSupplier = chooseProductList.value.filter(item => item.supplierId != formRes.supplierId)
			if (isSupplier.length > 0) {
				const isSupplierProduct = isSupplier.map(item => item.productName).join(',')
				uni.showModal({
					title: '提示',
					content: `${isSupplierProduct}不属于所选供应商`,
					showCancel: false
				})
				return false
			}
			const allProductList = chooseProductList.value.filter(item => Number(item.productCount) > 0).map(item => {
				return {
					id: item.productId,
					moreSpec: item.supplierProduct.moreSpec,
					name: item.productName,
					number: item.productCount,
					purchasePrice: item.purchasePrice,
					specList: [],
					subtotal: item.purchaseMoney,
					supplierProductId: item.supplierProduct.id,
					typeName: item.typeName,
					unit: item.productUnit
				}
			})
			if (allProductList.length === 0) {
				return uni.$u.toast('商品不能为空')
			}
			const params = { 
				...formRes,
				allProductList
			}
			isSubmit.value = true
			purchaseOrderAdd(params).then(async (res) => {
				modal.showToast(res.msg)
				await uni.$u.sleep(1000)
				isSubmit.value = false
				clear()
				setStore.purchaseOrder = {}
				uni.$emit('refreshList');  // 触发刷新事件
				uni.navigateBack({
					delta: 1
				})
			}).catch(err => {
				isSubmit.value = false
			})
		})
	}
	// 清空
	const clear = () => {
		formData.value = {
			allPrice: 0,
			discountPrice: '',
			otherPrice: '',
			remark: '',
			supplierId: '',
			warehouseId: ''
		}
	}
	const changeProductCount = (e, row) => {
		chooseProductList.value[row.rowIndex].productCount = e
		chooseProductList.value[row.rowIndex].purchaseMoney = purchaseMoney(chooseProductList.value[row.rowIndex].purchasePrice, e)
	}
	const purchaseMoney = (purchasePrice, productCount) => {
		return purchasePrice && productCount ? Decimal(productCount).mul(Decimal(purchasePrice)).toNumber() : 0
	}
	// 商品选择
	const showProduct = ref(false)
	const addFun = () => {
		showProduct.value = true
	}
	const closeProduct = () => {
		showProduct.value = false
	}
	const changeProduct = (list) => {
		for(let i = 0; i < list.length; i++) {
			const filter = chooseProductList.value.find(item => item.productId === list[i].productId)
			if (!filter) {
				chooseProductList.value.push({
					productCount: 0,
					productId: list[i].productId,
					productName: list[i].productName,
					productUnit: list[i].unit,
					supplierId: list[i].supplierId,
					supplierName: list[i].supplierName,
					typeName: list[i].typeName,
					purchasePrice: list[i].purchasePrice,
					supplierProduct: list[i],
					purchaseMoney: 0
				})
			}
		}
	}
	// 删除商品
	const delFun = (row) => {
		chooseProductList.value.splice(row.rowIndex, 1)
	}
	
	// 库存查询
	const showStorage = ref(false)
	const searchProductName = ref('')
	const searchFun = (row) => {
		const productNameArr = row.productName.split(' ')
		if (formData.value.warehouseId) {
			searchProductName.value = row.productName.split(' ')?.[0] || ''
			showStorage.value = true
		} else {
			uni.$u.toast('请选择仓库')
		}
	}
	const closeStorage = () => {
		showStorage.value = false
	}
	
	watch(() => chooseProductList.value, (nval, oval) => {
		totalMoney()
	},{ deep: true })
	watch(() => formData.value.otherPrice, (nval, oval) => {
		totalMoney()
	})
	watch(() => formData.value.discountPrice, (nval, oval) => {
		totalMoney()
	})
	
	// 计算总金额
	const totalMoney = () => {
		const goodsMoney = chooseProductList.value.reduce((prev, cur, index, arr) => {
			return Decimal(prev).add(cur.purchaseMoney).toNumber()
		}, 0)
		formData.value.allPrice = Decimal(goodsMoney).add(Decimal(formData.value.otherPrice || 0)).sub(Decimal(formData.value.discountPrice || 0)).toNumber()
	}
</script>

<style scoped lang="scss">
	.search {
		margin-top: 0;
	}
	.table-td-input {
	}
	.price {
		font-size: 28rpx;
	}
	.operate {
		margin-left: auto;
	}
	:deep(.table-cell) {
		&:last-child {
			align-self: center;
		}
	}
	.formRef-btn {
		padding: 0rpx 20rpx 40rpx;
	}
</style>
